<?php

require_once (APPLICATION_PATH . "/library/excelreader/class.read_excel.php");


/**
 * ClienteController
 * 
 * @package Sgit 
 * @author Juan Manuel Martinez Carrillo
 * @copyright Juan Manuel Martinez Carrillo
 * @version 2012
 * @access public
 * @revision 17/02/2012 8:53:55
 */

class SlaController extends Sgit_Controller_Action
{

    protected $_checkAcceso = FALSE;
    
    public function _begin()
    {
        //cache
        $frontendOptions = array('lifetime' => 86400*5, // 10 hora
            'automatic_serialization' => true);
        $backendOptions = array('cache_dir' => APPLICATION_PATH . '/tmp/');

        // getting a Zend_Cache_Core object
        $this->_cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);
        
        $this->_cache->clean(Zend_Cache::CLEANING_MODE_OLD);
    }
    
    
    
    public function indexAction()
    {

        set_time_limit(500);

        if ($this->_request->isPost())
        {

            if (!empty($_FILES))
            {
                $fileNameTemp = $_FILES['fileToUpload']['tmp_name'];


                $data = new Spreadsheet_Excel_Reader();
                $data->read($fileNameTemp);


                foreach ($data->boundsheets as $k => $v)
                {

                    $numRowsInFile = count($data->sheets[$k]['cells']);
                    $numColsInRow = count($data->sheets[$k]['cells'][1]);



                    if ($numRowsInFile != 0 && $numColsInRow != 0)
                    {

                        $this->_calcular($data->sheets[$k], $v['name']);
                    }
                }
                    

                $md5 = 'datalogger_todo';
                $this->_cache->save($this->_log,$md5 );

            }
        }

        $directory = APPLICATION_PATH . "/tmp";
        $iterator = new DirectoryIterator($directory);
        foreach ($iterator as $fileinfo)
        {
            if ($fileinfo->isFile())
            {
                if (strpos($fileinfo->getFilename(), 'zend_cache---datalogger') !== false)
                {
                    $hora = $fileinfo->getMTime();
                    $files[$hora] = str_replace('zend_cache---', '', $fileinfo->getFilename());

                }
            }
            
            ksort($files);
        }

        $this->view->files = $files;


    }

    public function exportaAction()
    {

        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);

        $file=$this->_getParam('file');
        

        $rows= $this->_cache->load($file);

        $row0=$rows[0];
        
        $date=new Zend_Date($row0['fecha'],Zend_Date::ISO_8601);
        $fecha=$date->get('MMM yyyy');
        



        $plantilla_xls = $this->_actionName;

        $xml = $this->_getXml($plantilla_xls);
        $excel = new Sgit_Excel();
        $excel->setColumnas($xml['columnas']);


        if ($this->_pdfTitle)
            $excel->SetTitle($this->_pdfTitle);
        else
            $excel->SetTitle($xml['config']['title']);

            $excel->SetSubTitle($row0['datalogger'].' '.$fecha);
     


        $filename = ($xml['config']['file']) ? $xml['config']['file'] : $this->_controllerName;
        $excel->render($rows, $row0['datalogger'].' '.$fecha);
        if ($return)
            return true;


    }


    private function _calcular($hoja, $name)
    {

        $numRowsInFile = count($hoja['cells']);
        $numColsInRow = count($hoja['cells'][1]);
        $startCountAt = 2;
        $datalogger = $hoja['cells'][1][1];


 

        $filter = new Zend_Filter_Alnum();
        $return = $filter->filter($name);


        $md5 = 'datalogger_' . $return;


        for ($i = $startCountAt; $i <= $numRowsInFile; $i++)
        {
            $f = $hoja['cells'][$i][2];

            if (empty($f))
                continue;

            $date = new Zend_Date($f,Zend_Date::ISO_8601);

            $fecha = $date->get('yyyy-MM-dd');
            $hora = $date->get('HH:mm');

            $fila[$fecha]['humedad'][$hora] = $hoja['cells'][$i][3];
            $fila[$fecha]['temperatura'][$hora] = $hoja['cells'][$i][4];
        }


        foreach ($fila as $k => $v)
        {
            
            $media_humedad = array_sum($v['humedad']) / count($v['humedad']);
            $media_temperatura = array_sum($v['temperatura']) / count($v['temperatura']);
            
            $record['datalogger'] = trim($name);
            $record['fecha'] = $k;
            $record['humedad_max'] = max($v['humedad']);
            $record['humedad_hora_max'] = $this->max_key($v['humedad']);
            $record['humedad_min'] = min($v['humedad']);
            $record['humedad_hora_min'] = $this->min_key($v['humedad']);
            $record['humedad_media1'] = $media_humedad;
            $record['temperatura_max'] = max($v['temperatura']);
            $record['temperatura_hora_max'] = $this->max_key($v['temperatura']);
            $record['temperatura_min'] = min($v['temperatura']);
            $record['temperatura_hora_min'] = $this->min_key($v['temperatura']);
            $record['temperatura_media1'] = $media_temperatura;
            
            
            $this->_log[] = $record;

        }
        
        $this->_log[] = array();
        $this->_log[] = array();

       // $this->_cache->save($log, $md5);

    }


    function max_key($array)
    {
        foreach ($array as $key => $val)
        {
            if ($val == max($array))
                return $key;
        }
    }

    function min_key($array)
    {
        foreach ($array as $key => $val)
        {
            if ($val == min($array))
                return $key;
        }
    }

}
